<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/10/27 11:44:17 $)
// $RCSfile: functions_sqlsearch.php,v $ : $Revision: 1.5 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Build the SQL For Searching on a field
*/
function buildSQLSearch($field, $query, $noparity = false)
{
	// Sanitize the text
	if ($noparity)
	{
		$stopdata = array("#\s+#s", "#(\r\n|\r|\n)#s");
		$replacewith = array(" ", " ");
	} else {
		$stopdata = array("#\s+#s", "#(\r\n|\r|\n)#s", "/[^a-zA-Z0-9.@\-\_\s]/");
		$replacewith = array(" ", " ", "");
	}
	$_query = preg_replace($stopdata, $replacewith, $query);

	// Split the query into words using spaces
	$words = explode(" ", $_query);
	if (!count($words))
	{
		$words = array($query);
	}

	$_sql = array();
	foreach ($words as $key=>$val)
	{
		$prefix = substr($val,0,1);
		$nprefixword = substr($val, 1);
		if ($prefix == "-")
		{
			$_sql[] = addslashes($field)." NOT LIKE '%". addslashes($nprefixword) ."%'";
		} else if ($prefix == "+") {
			$_sql[] = addslashes($field)." LIKE '%". addslashes($nprefixword) ."%'";
		} else {
			$_sql[] = addslashes($field)." LIKE '%". addslashes($val) ."%'";
		}
	}

	if (!count($_sql))
	{
		return false;
	}

	return implode(" AND ", $_sql);
}
?>